<template>
  <div class="aa">
    <div style="padding-left: 30px; margin-bottom: 34px">
      <el-page-header @back="cancel" content="添加/编辑"></el-page-header>
    </div>
    <el-form
      :model="form"
      label-width="110px"
      ref="ruleForm"
      style="margin-left: 20px"
      :rules="rules"
    >
      <div class="common">
        <el-form-item label="所属分类：" prop="phtId">
          <el-select v-model="form.phtId" style="width: 100%">
            <el-option
              v-for="item in infoType"
              :value="item.pid"
              :key="item.pid"
              :label="item.pname"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="作者：" prop="phAuthor">
          <el-input v-model="form.phAuthor"></el-input>
        </el-form-item>
      </div>
      <div class="common">
        <el-form-item label="标题：" prop="phTitle">
          <el-input v-model="form.phTitle"></el-input>
        </el-form-item>
        <el-form-item label="来源：" prop="phSource">
          <el-input v-model="form.phSource"></el-input>
        </el-form-item>
      </div>
      <div class="common">
        <el-form-item label="概述：" prop="phSummarize">
          <el-input type="textarea" v-model="form.phSummarize"></el-input>
        </el-form-item>
        <el-form-item label="关键字：" prop="phKeyWork">
          <el-input v-model="form.phKeyWork"></el-input>
        </el-form-item>
      </div>
      <div class="common">
        <div class="commons">
          <el-form-item label="排序：" prop="phSort">
            <el-input
              :min="1"
              type="number"
              v-model.number="form.phSort"
              style="width: 100px"
            ></el-input>
          </el-form-item>
          <el-form-item label="置顶：">
            <el-checkbox v-model="form.phTop" name="name"></el-checkbox>
          </el-form-item>
          <el-form-item label="列表隐藏：">
            <el-checkbox v-model="form.phConceal" name="name"></el-checkbox>
          </el-form-item>
        </div>
        <el-form-item
          style="margin-left: 30%"
          label="详情："
          prop="phParticulars"
        >
          <el-input type="textarea" v-model="form.phParticulars"></el-input>
        </el-form-item>
      </div>
      <div class="common">
        <el-form-item label="封面图:">
          <el-upload
            class="upload-demo"
            drag
            v-loading="loading"
            :on-success="picUpload"
            :before-upload="beforeUpload"
            :action='$env.BASE_URL+"/homework/zhty/public/import_file"'
            multiple
            :headers="{
              'access-token': $store.state.user.TOKEN,
            }"
          >
            <div v-if="!form.phPic">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
                <div class="el-upload__tip" slot="tip">只能上传图片文件</div>
              </div>
            </div>
            <img
              style="
                width: auto;
                height: auto;
                max-height: 100%;
                max-width: 100%;
              "
              v-if="form.phPic"
              :src="$store.state.user.BASE_URL + form.phPic"
              alt=""
            />
          </el-upload>
        </el-form-item>
        <el-form-item label="视频:">
          <el-upload
            class="upload-demo"
            drag
            v-loading="loading1"
            :on-success="videoUpload"
            :before-upload="beforeUpload1"
            :action='$env.BASE_URL+"/homework/zhty/public/import_file"'
            multiple
            :headers="{
              'access-token': $store.state.user.TOKEN,
            }"
          >
            <div v-if="!form.phVideo">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
            </div>
            <video
              style="
                width: auto;
                height: auto;
                max-height: 100%;
                max-width: 100%;
              "
              v-if="form.phVideo"
              :src="$store.state.user.BASE_URL + form.phVideo"
            />
          </el-upload>
        </el-form-item>
      </div>
      <div class="common">
        <el-form-item label="链接地址：" prop="phLinkAddress">
          <el-input v-model="form.phLinkAddress"></el-input>
        </el-form-item>
        <el-form-item label="链接有效期：" prop="time">
          <el-date-picker
            style="width: 100%"
            v-model="form.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
      </div>
    </el-form>
    <div class="btn" style="margin-left: 10%">
      <el-button size="small" :loading="disable" type="primary" @click="save">{{
        disable ? "加载中" : "提交"
      }}</el-button>
    </div>
  </div>
</template>

<script>
import { addSportInfo, infoType } from "@/api/information";
import moment from "moment";
export default {
  name: "infoForm",
  components: {},

  props: {},
  data() {
    return {
      disable: false,
      form: {
        item: null,
        phtId: "",
        phTitle: "",
        phSummarize: "",
        phSort: 1,
        phTop: null,
        phPic: "",
        phVideo: "",
        phConceal: null,
        phAuthor: "",
        phSource: "",
        phKeyWork: "",
        phParticulars: "",
        phLinkAddress: "",
        time: [],
      },
      infoType: [],
      loading: false,
      loading1: false,
      phId: null,
      rules: {
        phtId: [
          {
            required: true,
            message: "请选择",
          },
        ],
        phTitle: [
          {
            required: true,
            message: "此处是必填项",
          },
          {
            min: 2,
            max: 50,
            message: "长度必须在2-50个之间",
            trigger: "blur",
          },
        ],
        phSummarize: [
          {
            required: true,
            message: "此处是必填项",
          },
          {
            min: 2,
            max: 200,
            message: "长度必须在2-200个之间",
            trigger: "blur",
          },
        ],

        phAuthor: [
          {
            required: true,
            message: "此处是必填项",
          },
          {
            min: 2,
            max: 10,
            message: "长度必须在2-10个之间",
            trigger: "blur",
          },
        ],
        phSource: [
          {
            required: true,
            message: "此处是必填项",
          },
          {
            min: 2,
            max: 50,
            message: "长度必须在2-50个之间",
            trigger: "blur",
          },
        ],
        phKeyWork: [
          {
            required: true,
            message: "此处是必填项",
          },
          {
            min: 2,
            max: 10,
            message: "长度必须在2-10个之间",
            trigger: "blur",
          },
        ],
        phParticulars: [
          {
            required: true,
            message: "此处是必填项",
          },
          {
            min: 2,

            message: "最少2个长度",
            trigger: "blur",
          },
        ],
        phLinkAddress: [
          {
            required: true,
            message: "此处是必填项",
          },
          {
            min: 2,
            max: 300,
            message: "长度必须在2-300个之间",
            trigger: "blur",
          },
        ],
        time: [
          {
            required: true,
            message: "此处是必填项",
          },
        ],
      },
    };
  },
  computed: {},
  watch: {},
  created() {
    this.handler();
    this.getInfoType();
  },
  mounted() {},
  methods: {
    handler() {
      if (this.$route.query.isEdit) {
        this.form = {
          ...JSON.parse(this.$route.query.item),
          phConceal: !!JSON.parse(this.$route.query.item).phConceal,
          phTop: !!JSON.parse(this.$route.query.item).phTop,
          phtId: JSON.parse(this.$route.query.item).phtId + "",
          time: [
            JSON.parse(this.$route.query.item).phLinkStartDate,
            JSON.parse(this.$route.query.item).phLinkEndDate,
          ],
        };
      }
    },
    beforeUpload(file) {
      this.loading = true;
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const types = ["jpeg", "jpg", "png"];
      if (!types.includes(fileSuffix)) {
        this.$message.error(`文件只能是 ${types.join()} 格式!`);
        this.loading = false;
      }
      return types.includes(fileSuffix);
    },
    beforeUpload1(file) {
      this.loading1 = true;
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const types = [
        "avi",
        "mov",
        "mpg",
        "mpeg",
        "rmvb",
        "mp4",
        "flv",
        "rm",
        "mkv",
      ];
      if (!types.includes(fileSuffix)) {
        this.$message.error(`文件只能是 ${types.join()} 格式!`);
        this.loading1 = false;
      }
      return types.includes(fileSuffix);
    },
    videoUpload(e) {
      if (e.code === 200) {
        this.form.phVideo = e.result.pic;
      } else if (e.code === 401) {
        this.$router.replace("/");
        this.$message.error("您的身份信息已过期，请重新登录");
        sessionStorage.removeItem("userInfo");
        sessionStorage.removeItem("token");
        this.$store.commit("user/SET_TOKEN", "");
      } else {
        this.$message.error(e.message);
      }
      this.loading1 = false;
    },
    picUpload(e) {
      if (e.code === 200) {
        this.form.phPic = e.result.pic;
      } else if (e.code === 401) {
        this.$router.replace("/");
        this.$message.error("您的身份信息已过期，请重新登录");
        sessionStorage.removeItem("userInfo");
        sessionStorage.removeItem("token");
        this.$store.commit("user/SET_TOKEN", "");
      } else {
        this.$message.error(e.message);
      }
      this.loading = false;
    },
    getInfoType() {
      let data = {
        userId: this.$store.state.user.USER_INFO.id,
      };
      infoType(data).then((res) => {
        if (res.code == 200) {
          this.infoType = res.result;
        }
      });
    },
    save() {
      // 对所有表单项
      this.$refs["ruleForm"].validate(async (valid) => {
        if (valid) {
          this.disable = true;
          let data = {
            userId: this.$store.state.user.USER_INFO.id,
            phId: this.$route.query.item
              ? JSON.parse(this.$route.query.item).phId
              : null,
            phtId: parseInt(this.form.phtId),
            phTitle: this.form.phTitle,
            phSummarize: this.form.phSummarize,
            phSort: this.form.phSort,
            phTop: this.form.phTop ? "1" : "0",
            phPic: this.form.phPic,
            phVideo: this.form.phVideo,
            phConceal: this.form.phConceal ? "1" : "0",
            phAuthor: this.form.phAuthor,
            phSource: this.form.phSource,
            phKeyWork: this.form.phKeyWork,
            phParticulars: this.form.phParticulars,
            phLinkAddress: this.form.phLinkAddress,
            phLinkStartDate: moment(this.form.time[0]).format(
              "YYYY-MM-DD HH:mm:ss"
            ),
            phLinkEndDate: moment(this.form.time[1]).format(
              "YYYY-MM-DD HH:mm:ss"
            ),
          };
          addSportInfo(data).then((res) => {
            if (res.code == 200) {
              this.$message.success("保存成功");
              this.$router.push({
                path: "/sportsConsulting/information",
              });
            } else {
              this.$message.error(res.message);
            }
          });
          //  this.$emit("back")
        } else {
          return false;
        }
      });
    },
    cancel() {
      this.$router.push({
        path: "/sportsConsulting/information",
      });
    },
  },
};
</script>

<style scoped lang="scss">
.btn {
  display: flex;
  justify-content: center;
}
.common {
  display: flex;
  justify-content: space-between;
  width: 100%;
  .el-form-item {
    flex: 1;
  }
  .el-upload {
    width: 100%;
    ::v-deep .el-upload-dragger {
      width: 100%;
    }
  }
}
.commons {
  display: flex;
  width: 20%;
}
.aa {
  padding: 0 30px;
}

::v-deep .el-upload-list__item {
  display: none;
}
::v-deep .el-upload--text {
  width: 100%;
}
::v-deep .el-upload-dragger {
  width: 100%;
}
::v-deep .el-upload__tip {
  margin-top: -12px;
}
</style>
